package asteroids.model.programs.expressions.BasicExpressions;
import java.util.Map;

import asteroids.model.programs.expressions.BasicExpression;
import asteroids.model.programs.types.Type;

/**
 * A class representing variables
 * 
 * @author r0297214
 *
 */
public class Variable extends BasicExpression {
	
	public Variable(String name, int line, int column){
		super(line, column);
		this.name = name;
	}
	
	
	@Override
	public BasicExpression getResult(){
		BasicExpression result = getReference();
		if (result == null) throw new NullPointerException();
		else return result;
	}
	
	private BasicExpression getReference(){
		return getStatement().getProgram().getVariableReference(name);
	}
	
	@Override
	public String toString() {
		return getReference().toString();
	}
	
	public String getName(){
		return name;
	}
	private String name;
	
	
	@Override
	public Type getType(){
		return getStatement().getProgram().getGlobals().get(name);
	}	
	
	@Override
	public String typeCheckExpression(String errorMessage){
		Map<String, Type> globals = getStatement().getProgram().getGlobals();
		String newErrorMessage = null;
		
		if(!globals.containsKey(getName())){ //The variable is not within the global variable map
			if(getStatement().getNextStart() != null){ //Means that is in the main statement, and thus should be a global variable.
				newErrorMessage = ("The variable mentioned at line " + getLine() + 
									" and column " + getColumn() + " is not a global variable\n");		
			}
		}
		
		if(newErrorMessage != null && errorMessage != null) newErrorMessage = errorMessage + newErrorMessage;
		return newErrorMessage;
		
	}
}
